package evs.gateway;

import java.util.List;

import evs.location.EntityDom;

public class ResultMerger {

	public static void merge( EntityDom from, EntityDom into, String itemType )
	{
		assert from.name.equals("results");
		assert into.name.equals("results");
		
		while ( !from.children.isEmpty() )
		{
			EntityDom item = from.children.get( 0 );
			
			assert item.name.equals(itemType);
			assert _hasIdElement( item );
			
			from.removeChild( item );
			
			if ( !_isAlreadyContained( item, into.children ) )
			{
				into.addChild(item);
			}
		}
	}

	private static boolean _isAlreadyContained( EntityDom item, List<EntityDom> otherItems ) 
	{
		String itemId = _getId( item );
        assert itemId != null;
		
		for ( EntityDom otherItem : otherItems )
		{
		    if ( itemId.equals( _getId( otherItem ) ) )
		    	return true;
		}
		
		return false;
	}

	private static String _getId(EntityDom item) {

		for ( EntityDom childElement : item.children )
			if ( childElement.name.equalsIgnoreCase( "id" ) )
				return childElement.value;
		
		return null;
	}

	private static boolean _hasIdElement(EntityDom item) {

		for ( EntityDom child : item.children )
		{
			if ( child.name.equalsIgnoreCase( "id" ) )
				return true;
		}

		return false;
	}
}
